package com.tianxinweb.controller;

import com.alibaba.fastjson.JSON;
import com.aliyuncs.DefaultAcsClient;
import com.aliyuncs.IAcsClient;
import com.aliyuncs.dysmsapi.model.v20170525.SendSmsRequest;
import com.aliyuncs.dysmsapi.model.v20170525.SendSmsResponse;
import com.aliyuncs.exceptions.ClientException;
import com.aliyuncs.http.MethodType;
import com.aliyuncs.profile.DefaultProfile;
import com.aliyuncs.profile.IClientProfile;
import com.fasterxml.jackson.annotation.JsonTypeInfo;
import com.tianxinweb.config.AlidayuConfig;
import com.tianxinweb.entity.Result;
import com.tianxinweb.entity.Sendsms;
import com.tianxinweb.enums.ResultEnum;
import com.tianxinweb.exception.MyException;
import com.tianxinweb.service.SendsmsService;
import com.tianxinweb.utils.CommonUtil;
import com.tianxinweb.utils.IpUtil;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpSession;
import java.util.HashMap;
import java.util.Map;
import java.util.Timer;
import java.util.TimerTask;

/**
 * <p>
 *  前端控制器
 * </p>
 *
 * @author cboy
 * @since 2018-08-07
 */
@RestController
@RequestMapping("/sms")
public class SmsController {

    private Logger logger = LoggerFactory.getLogger(SmsController.class);

    @Autowired
    private AlidayuConfig config;
    @Autowired
    private SendsmsService sendsmsService;

    /**
     * 阿里大鱼短信发送，支持1条/分钟，5条/小时，累计10条/天
     * @param phone
     * @param httpServletRequest
     * @return
     * @throws ClientException
     */
    @RequestMapping("send")
    public Result send(@RequestParam("phone") String phone, HttpServletRequest httpServletRequest,
                       HttpSession session) throws ClientException {
        if(!CommonUtil.validatePhone(phone)){
            throw new MyException(ResultEnum.PARAMETER_FORMAT_ERROR);
        }

        //设置超时时间-可自行调整
        System.setProperty("sun.net.client.defaultConnectTimeout", "10000");
        System.setProperty("sun.net.client.defaultReadTimeout", "10000");
        //初始化ascClient需要的几个参数
        final String product = "Dysmsapi";//短信API产品名称（短信产品名固定，无需修改）
        final String domain = "dysmsapi.aliyuncs.com";//短信API产品域名（接口地址固定，无需修改）

        IClientProfile profile = DefaultProfile.getProfile("cn-hangzhou", config.getAccessKeyId(),
                config.getAccessKeySecret());
        DefaultProfile.addEndpoint("cn-hangzhou", "cn-hangzhou", product, domain);
        IAcsClient acsClient = new DefaultAcsClient(profile);

        //组装请求对象
        SendSmsRequest request = new SendSmsRequest();
        //使用post提交
        request.setMethod(MethodType.POST);
        //必填:待发送手机号。支持以逗号分隔的形式进行批量调用，批量上限为1000个手机号码,批量调用相对于单条调用及时性稍有延迟,验证码类型的短信推荐使用单条调用的方式；发送国际/港澳台消息时，接收号码格式为00+国际区号+号码，如“0085200000000”
        request.setPhoneNumbers(phone);
        //必填:短信签名-可在短信控制台中找到
        request.setSignName(config.getSignName());
        //必填:短信模板-可在短信控制台中找到，发送国际/港澳台消息时，请使用国际/港澳台短信模版
        request.setTemplateCode(config.getTemplateCode());
        //可选:模板中的变量替换JSON串,如模板内容为"亲爱的${name},您的验证码为${code}"时,此处的值为
        //友情提示:如果JSON中需要带换行符,请参照标准的JSON协议对换行符的要求,比如短信内容中包含\r\n的情况在JSON中需要表示成\\r\\n,否则会导致JSON在服务端解析失败
        int randNum = (int)((Math.random()*9+1)*100000);
        if(config.getTemplateParam() != null){
            Map<String,String> map = new HashMap<>();
            map.put(config.getTemplateParam(),randNum+"");
            request.setTemplateParam(JSON.toJSONString(map));
        }

        //请求失败这里会抛ClientException异常
        SendSmsResponse sendSmsResponse = acsClient.getAcsResponse(request);
        //请求成功
        if(sendSmsResponse.getCode() != null && sendSmsResponse.getCode().equals("OK")) {
            String ip = IpUtil.getIp(httpServletRequest);
            Sendsms sendsms = new Sendsms();
            sendsms.setPhone(phone);
            sendsms.setIpAddr(ip);
            sendsms.setCheckcode(randNum+"");
            //保存发送记录
            sendsmsService.insert(sendsms);

            session.setAttribute(phone, randNum+"");
            Timer timer = new Timer(true);
            timer.schedule(new TimerTask() {

                @Override
                public void run() {
                    session.removeAttribute(phone);
                    timer.cancel();
                }
            }, 300000);//5分钟之后清除session中的验证码
        }else if(sendSmsResponse.getCode().equals("isv.BUSINESS_LIMIT_CONTROL")){
            new MyException(ResultEnum.BUSINESS_LIMIT_CONTROL);
        }else{
            logger.error(sendSmsResponse.getMessage());
            return Result.fail();
        }

        return Result.success();
    }
}
